import sys
from glob import glob
import pandas as pd
import os

from gooey import Gooey, GooeyParser

# https://hub.fastgit.org/chriskiehl/Gooey/issues/520
import codecs

if sys.stdout.encoding != 'UTF-8':
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'UTF-8':
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')


def combine_excel(path, save_path):
    data = {}
    files = glob(f"{path}/**/[!~]*.xls*", recursive=True)
    for i, file in enumerate(files, 1):
        for name, df in pd.read_excel(file, sheet_name=None).items():
            data.setdefault(name, []).append(df)
        yield f"合并进度：{i}/{len(files)}"

    # 获取文件目录的最后一个目录名
    save_name_prefix = os.path.split(os.path.splitext(path)[0])[1]
    if os.path.exists(f"{save_path}/{save_name_prefix}.xlsx"):
        os.remove(f"{save_path}/{save_name_prefix}.xlsx")

    with pd.ExcelWriter(f'{save_path}/{save_name_prefix}.xlsx') as write:
        items = data.items()
        for i, (name, dfs) in enumerate(items, 1):
            pd.concat(dfs).to_excel(write, name, index=False)
            yield f"保存进度：{i}/{len(items)}"


@Gooey(program_name='Excel批量合并 @火柴科技 \t V1.0',
       language='chinese',
       enconding='utf-8',
       progress_regex=r"^..进度：(?P<current>\d+)/(?P<total>\d+)$",
       progress_expr="current / total * 100",
       timing_options={
           'show_time_remaining': False,
           'hide_time_remaining_on_complete': True,
       })
def main():
    description_str = '''1. 支持多文件多sheet合并 \n2. 支持xlsx和xls类型文件 \n3. 不支持带样式表头文件
    '''
    parser = GooeyParser(description=description_str)
    parser.add_argument('input_path', help="被合并的Excel文件目录", widget="DirChooser")
    parser.add_argument('save_path', help="合并后保存的文件目录", widget="DirChooser")
    args = parser.parse_args()
    print("输入路径：", args.input_path)
    print("保存位置：", args.save_path)
    for msg in combine_excel(args.input_path, args.save_path):
        print(msg)
    print("合并完成！")


if __name__ == '__main__':
    main()
